package com.ceam.biz.activiti.controller;

import cn.hutool.core.convert.ConverterRegistry;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ceam.biz.activiti.dto.LeaveDto;
import com.ceam.biz.activiti.dto.TaskDto;
import com.ceam.biz.activiti.entity.BizAudit;
import com.ceam.biz.activiti.entity.BizBusiness;
import com.ceam.biz.activiti.service.IBizAuditService;
import com.ceam.biz.activiti.service.IBizBusinessService;
import com.ceam.biz.activiti.service.TaskService;
import com.ceam.biz.activiti.vo.BizAuditVo;
import com.ceam.biz.activiti.vo.RuTaskVo;
import com.ceam.biz.system.service.UserService;
import com.ceam.core.base.api.R;
import com.ceam.core.log.annotation.OperLog;
import com.ceam.core.security.util.SecurityUtil;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import org.activiti.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @description 任务 controller
 */
@RestController
@AllArgsConstructor
@RequestMapping("/activiti/task")
public class TaskController {
    private final TaskService taskService;

    @Autowired
    private org.activiti.engine.TaskService aTaskService;

    @Autowired
    private IBizAuditService bizAuditService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IBizBusinessService businessService;

    @Autowired
    private UserService userService;

    @Autowired
    private MapperFactory mapperFactory;

    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        IPage<RuTaskVo> taskIPage = taskService.list(params);
        return R.ok(taskIPage.getRecords(), taskIPage.getTotal());
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(taskService.getTaskById(id));
    }

    @OperLog("任务审批")
    @PostMapping("/checkTask")
    public R checkTask(@RequestBody LeaveDto leaveDto) {
        return R.ok(taskService.checkTask(leaveDto));
    }

    @PostMapping("/audit")
    public R audit(@RequestBody BizAuditVo bizAuditVo)
    {
        // 设置流程变量并进行审核
        HashMap<String, Object> variables = Maps.newHashMap();
        variables.put("result", bizAuditVo.getResult());
        aTaskService.complete(bizAuditVo.getTaskId(), variables);

        // 插入审核记录、业务记录，可能会设置下一节点审核人
        bizAuditVo.setAuditor(SecurityUtil.getUser().getUsername());
        Integer id = SecurityUtil.getUser().getId();
        //ConverterRegistry converterRegistry = ConverterRegistry.getInstance();
        //Long convert = converterRegistry.convert(Long.class, id);
        bizAuditVo.setAuditorId(Long.parseLong(id.toString()));
        // 映射器(防止字段不匹配问题)， vo -> entity
        MapperFacade facade = mapperFactory.getMapperFacade();
        BizAudit bizAudit = facade.map(bizAuditVo, BizAudit.class);

        // 插入审核记录
        bizAuditService.insertBizAudit(bizAudit);

        //  根据流程实例ID设置下一个审核人，并更新biz_business表
        BizBusiness bizBusiness = new BizBusiness().setId(bizAuditVo.getBusinessKey())
                .setProcInstId(bizAuditVo.getProcInstId());
        businessService.setAuditor(bizBusiness, bizAuditVo.getResult(), SecurityUtil.getUser().getId());
        return R.ok();
    }

    @OperLog("任务审批意见")
    @GetMapping("/commitList/{id}")
    public R commitList(@PathVariable String id) {
        return R.ok(taskService.commitList(id));
    }

    @OperLog("任务追踪")
    @GetMapping("/track/{id}")
    public ResponseEntity trackImage(@PathVariable String id) {
        InputStream imageStream = taskService.trackImage(id);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity(IoUtil.readBytes(imageStream), headers, HttpStatus.CREATED);
    }

}
